package com.doit.doit47;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;

public class _04_mysql中的事务用jdbc如何操作 {
    public static void main(String[] args) throws SQLException {

        //往两张表里面写数据 将这两个动作绑定成一个事务
        //jdbc的练级额对象
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test01", "root", "123456");
        conn.setAutoCommit(false);
        PreparedStatement user_pps = conn.prepareStatement("insert into user values(?,?,?,?)");
        PreparedStatement off_pps = conn.prepareStatement("insert into off valuse(?,?)");

        ArrayList<String> list = new ArrayList<>();
        list.add("female");
        list.add("male");
        list.add("no_male");
        //给这两个sql进行赋值操作，然后执行
        for (int i = 0; i < 10; i++) {
            //开启事务

            try {
                //首先给第一个pps对象设置值
                user_pps.setInt(1, i);
                user_pps.setString(2, RandomStringUtils.randomAlphabetic(10));
                user_pps.setInt(3, RandomUtils.nextInt(10, 80));
                user_pps.setString(4, list.get(RandomUtils.nextInt(0, 3)));
                user_pps.execute();

                off_pps.setInt(1, i);
                off_pps.setInt(2, i);
                off_pps.execute();

                //提交事务
                conn.commit();
            } catch (SQLException e) {
                e.printStackTrace();

            }

        }
    }
}

